package com.sew.sewweb.api.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sew.sewweb.api.bean.DataDetails;
import com.sew.sewweb.api.bean.DataParam;
import com.sew.sewweb.bean.*;
import com.sew.sewweb.common.config.BaseConfig;
import com.sew.sewweb.common.utils.CallU8CUtils;
import com.sew.sewweb.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Guoan
 * @date 2024/3/7 - 16:05
 * 内蒙古能源系统对接OA
 */

@RestController
@RequestMapping("/sewweb")
@Tag(name = "对接接口",description = "sew对接三方系统接口")
public class SewOaController {

    private static final Logger log= LogManager.getLogger(SewOaController.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private OrgMemberService orgMemberService;
    @Autowired
    private OrgUnitService orgUnitService;
    @Autowired
    private CtpEnumService ctpEnumService;
    @Autowired
    private CtpAffairService ctpAffairService;
    @Autowired
    private CtpEnumItemService ctpEnumItemService;
    @Autowired
    private OrgPrincipalService orgPrincipalService;

    @Autowired
    private CtpContentAllService ctpContentAllService;

    @Autowired
    private CtpAttachmentService ctpAttachmentService;

    @Autowired
    private CtpCommentAllService ctpCommentAllService;

    @Autowired
    private ColSummaryService colSummaryService;

    @Autowired
    private Formmain0982Service formmain0982Service; //西安
    @Autowired
    private Formson0983Service formson0983Service;//西安

    @Autowired
    private Formmain0979Service formmain0979Service;//武汉
    @Autowired
    private Formson0980Service formson0980Service;//武汉

    @Autowired
    private Formmain0977Service formmain0977Service;//天津
    @Autowired
    private Formson0978Service formson0978Service;//天津

    @Autowired
    private Formmain0975Service formmain0975Service;//太原
    @Autowired
    private Formson0976Service formson0976Service;//太原

    @Autowired
    private Formmain0973Service formmain0973Service;//苏州
    @Autowired
    private Formson0974Service formson0974Service;//苏州

    @Autowired
    private Formmain0971Service formmain0971Service;//沈阳
    @Autowired
    private Formson0972Service formson0972Service;//沈阳

    @Autowired
    private Formmain0969Service formmain0969Service;//广州
    @Autowired
    private Formson0970Service formson0970Service;//广州

    @Autowired
    private Formmain0967Service formmain0967Service;//佛山
    @Autowired
    private Formson0968Service formson0968Service;//佛山



    //西安公司编码
    private static final String XABU = BaseConfig.getConfig().getString("BU.XA");
    //武汉公司编码
    private static final String WHBU = BaseConfig.getConfig().getString("BU.WH");
    //天津公司编码
    private static final String TJBU = BaseConfig.getConfig().getString("BU.TJ");
    //太远公司编码
    private static final String TYBU = BaseConfig.getConfig().getString("BU.TY");
    //苏州公司编码
    private static final String SZBU = BaseConfig.getConfig().getString("BU.SZ");
    //沈阳公司编码
    private static final String SYBU = BaseConfig.getConfig().getString("BU.SY");
    //广州公司编码
    private static final String GZBU = BaseConfig.getConfig().getString("BU.GZ");
    //佛山公司编码
    private static final String FSBU = BaseConfig.getConfig().getString("BU.FS");
    //表单字段
    //西安
    private static final String FIELDXA = BaseConfig.getConfig().getString("fieldname.XA");
    //武汉
    private static final String FIELDWH = BaseConfig.getConfig().getString("fieldname.WH");
    //天津
    private static final String FIELDTJ = BaseConfig.getConfig().getString("fieldname.TJ");
    //太原
    private static final String FIELDTY = BaseConfig.getConfig().getString("fieldname.TY");
    //苏州
    private static final String FIELDSZ = BaseConfig.getConfig().getString("fieldname.SZ");
    //沈阳
    private static final String FIELDSY = BaseConfig.getConfig().getString("fieldname.SY");
    //广州
    private static final String FIELDGZ = BaseConfig.getConfig().getString("fieldname.GZ");
    //佛山
    private static final String FIELDFS = BaseConfig.getConfig().getString("fieldname.FS");
    //系统的表名
    private static final String TABLENAMEXA = BaseConfig.getConfig().getString("tablename.XA");
    //武汉
    private static final String TABLENAMEWH = BaseConfig.getConfig().getString("tablename.WH");
    //天津
    private static final String TABLENAMETJ = BaseConfig.getConfig().getString("tablename.TJ");
    //太原
    private static final String TABLENAMETY = BaseConfig.getConfig().getString("tablename.TY");
    //苏州
    private static final String TABLENAMESZ = BaseConfig.getConfig().getString("tablename.SZ");
    //沈阳
    private static final String TABLENAMESY = BaseConfig.getConfig().getString("tablename.SY");
    //广州
    private static final String TABLENAMEGZ = BaseConfig.getConfig().getString("tablename.GZ");
    //佛山
    private static final String TABLENAMEFS = BaseConfig.getConfig().getString("tablename.FS");

    @PostMapping("dockOa")
    @Operation(summary = "对接业务系统接口",description = "对接业务系统接口")
    public String energy(@RequestBody String jsonParam){
        log.info("接受到的参数{}",jsonParam);
        ObjectMapper mapper = new ObjectMapper();
        try {
            String decode = URLDecoder.decode(jsonParam, "utf-8");
            log.info("转完之后的数据{}",decode);
            DataParam dataParam = mapper.readValue(decode, DataParam.class);
            OrgMemberEntity code = orgMemberService.getOne(new QueryWrapper<OrgMemberEntity>().eq("code", dataParam.getRequestor()));
            OrgPrincipalEntity memberId = orgPrincipalService.getOne(new QueryWrapper<>(new OrgPrincipalEntity()).eq("member_id", code.getId()));
            String token = CallU8CUtils.getOAToken(BaseConfig.getConfig().getString("getTokenUrlZS") + memberId.getLoginName());
            log.info("公司编码{}",dataParam.getBU());
            Map<String, Object> stringObjectMap = new HashMap<>();
            JSONObject assmbly = new JSONObject();
            String bu = null;
            if(dataParam.getBU().equals(XABU)){
                Formmain0982Entity field0002 = formmain0982Service.getOne(new QueryWrapper<Formmain0982Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    field0002.setField0115("1");
                    formmain0982Service.updateById(field0002);
                    CtpAffairEntity one = ctpAffairService.getOne(new QueryWrapper<CtpAffairEntity>().eq("form_recordid", field0002.getId()).eq("app", "999"));
                    if(one != null){
                        bu = dataParam.getBU();
                        stringObjectMap = this.assemblyData(dataParam);
                        assmbly = this.assmbly(field0002.getId(),stringObjectMap,XABU);
                        log.info("西安再次提交返回的数据={}",assmbly.toJSONString());
                    }
                }
            }else if(dataParam.getBU().equals(WHBU)){
                Formmain0979Entity field0002 = formmain0979Service.getOne(new QueryWrapper<Formmain0979Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    bu = dataParam.getBU();
                    stringObjectMap = this.assemblyData(dataParam);
                    assmbly = this.assmbly(field0002.getId(),stringObjectMap,WHBU);
                    log.info("武汉再次提交返回的数据={}",assmbly.toJSONString());
                }
            }else if(dataParam.getBU().equals(TJBU)){
                Formmain0977Entity field0002 = formmain0977Service.getOne(new QueryWrapper<Formmain0977Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    bu = dataParam.getBU();
                    stringObjectMap = this.assemblyData(dataParam);
                    assmbly = this.assmbly(field0002.getId(),stringObjectMap,TJBU);
                    log.info("天津再次提交返回的数据={}",assmbly.toJSONString());
                }
            }else if(dataParam.getBU().equals(TYBU)){
                Formmain0975Entity field0002 = formmain0975Service.getOne(new QueryWrapper<Formmain0975Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    bu = dataParam.getBU();
                    stringObjectMap = this.assemblyData(dataParam);
                    assmbly = this.assmbly(field0002.getId(),stringObjectMap,TYBU);
                    log.info("太原再次提交返回的数据={}",assmbly.toJSONString());
                }
            }else if(dataParam.getBU().equals(SZBU)){
                Formmain0973Entity field0002 = formmain0973Service.getOne(new QueryWrapper<Formmain0973Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    field0002.setField0097("1");
                    formmain0973Service.updateById(field0002);
                    CtpAffairEntity one = ctpAffairService.getOne(new QueryWrapper<CtpAffairEntity>().eq("form_recordid", field0002.getId()).eq("app", "999"));
                    if(one != null){
                        bu = dataParam.getBU();
                        stringObjectMap = this.assemblyData(dataParam);
                        assmbly = this.assmbly(field0002.getId(),stringObjectMap,SZBU);
                        log.info("苏州再次提交返回的数据={}",assmbly.toJSONString());
                    }

                }
            }else if(dataParam.getBU().equals(SYBU)){
                Formmain0971Entity field0002 = formmain0971Service.getOne(new QueryWrapper<Formmain0971Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    bu = dataParam.getBU();
                    stringObjectMap = this.assemblyData(dataParam);
                    assmbly = this.assmbly(field0002.getId(),stringObjectMap,SYBU);
                    log.info("沈阳再次提交返回的数据={}",assmbly.toJSONString());
                }
            }else if(dataParam.getBU().equals(GZBU)){
                Formmain0969Entity field0002 = formmain0969Service.getOne(new QueryWrapper<Formmain0969Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    bu = dataParam.getBU();
                    stringObjectMap = this.assemblyData(dataParam);
                    assmbly = this.assmbly(field0002.getId(),stringObjectMap,GZBU);
                    log.info("广州再次提交返回的数据={}",assmbly.toJSONString());
                }
            }else if(dataParam.getBU().equals(FSBU)){
                Formmain0967Entity field0002 = formmain0967Service.getOne(new QueryWrapper<Formmain0967Entity>().eq("field0002", dataParam.getPRNo()));
                if(field0002 == null){
                    stringObjectMap = this.assemblyData(dataParam);
                }else{
                    bu = dataParam.getBU();
                    stringObjectMap = this.assemblyData(dataParam);
                    assmbly = this.assmbly(field0002.getId(),stringObjectMap,FSBU);
                    log.info("佛山再次提交返回的数据={}",assmbly.toJSONString());
                }
            }

            if(!stringObjectMap.isEmpty() && assmbly.size() == 0){
                JSONObject jsonObject = new JSONObject(stringObjectMap);
                String sumbit = this.sumbit(jsonObject.toJSONString(), token,0,bu);
                log.info("新增返回的信息{}",sumbit);
            }else{
                log.info("再次发起进来啦!-------------------");
                String sumbit = this.sumbit(assmbly.toJSONString(), token, 1, bu);
                log.info("再次发起返回的信息{}",sumbit);
                this.remove(bu,dataParam.getPRNo());
            }
        }catch (Exception e){
            e.printStackTrace();
            String str = "流程发起失败," + e.getMessage();
            return str;
        }
        return "流程发起成功.";
    }


    public Map<String,Object> assemblyData(DataParam dataParam){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String,Object> map = new HashMap<>();//返回信息
        Map<String,String> ownerMap = new HashMap<>();//主表信息
        List<Map<String,String>> entityList = new ArrayList<>();//子表信息

        ownerMap.put("采购申请号",dataParam.getPRNo());
        ownerMap.put("申请日期",dataParam.getPRDate());
        ownerMap.put("工号",dataParam.getRequestedby());
        List<String> list = new ArrayList<>();
        list.add(dataParam.getRequestedby());
        list.add(dataParam.getRequestor());
        List<OrgMemberEntity> code = orgMemberService.list(new QueryWrapper<OrgMemberEntity>().in("code", list));
        for(OrgMemberEntity memberEntiyt : code){
            if(memberEntiyt.getCode().equals(dataParam.getRequestedby())){
                ownerMap.put("申请部门",memberEntiyt.getOrgDepartmentId().toString());
                ownerMap.put("申请人",memberEntiyt.getId().toString());
                ownerMap.put("申请人单位",memberEntiyt.getOrgAccountId().toString());

            }
            if(memberEntiyt.getCode().equals(dataParam.getRequestor())){
                ownerMap.put("填报人",memberEntiyt.getId().toString());
            }
        }
        ownerMap.put("实体",dataParam.getEntity());
        ownerMap.put("是否固定资产",dataParam.getCapital().equals("true") ? "固定资产" : "非固定资产");
        ownerMap.put("固定资产号",dataParam.getInvestmentNo());
        ownerMap.put("预算总金额",dataParam.getBudgetAmount());
        ownerMap.put("成本中心号",dataParam.getCCN());
        ownerMap.put("是否卖废品",dataParam.getSaleScrap().equals("true") ? "卖废品" : "非卖废品");
        ownerMap.put("急单",dataParam.getUrgent());
        ownerMap.put("用于",dataParam.getUsedFor());
        ownerMap.put("内部说明",dataParam.getExplanation());
        ownerMap.put("回退状态","1");
        log.info("预估总金额范围{}",dataParam.getEstimatedTotalAmountRange());
        ownerMap.put("预估总金额范围",dataParam.getEstimatedTotalAmountRange());
        ownerMap.put("预估总金额",dataParam.getEstimatedAmountMax());
        CtpEnumEntity one = ctpEnumService.getOne(new QueryWrapper<CtpEnumEntity>().eq("program_code", "CGShenQingLeiXing"));
        List<CtpEnumItemEntity> refEnumid = ctpEnumItemService.list(new QueryWrapper<CtpEnumItemEntity>().eq("ref_enumid", one.getId()));
        refEnumid.forEach(e ->{
            if("1".equals(dataParam.getPRTypeCode()) && e.getShowvalue().equals("EHS")){
                ownerMap.put("申请类型",e.getId().toString());
            }else if("2".equals(dataParam.getPRTypeCode()) && e.getShowvalue().equals("IT")){
                ownerMap.put("申请类型",e.getId().toString());
            }else if("3".equals(dataParam.getPRTypeCode()) && e.getShowvalue().equals("协议类付款的采购申请")){
                ownerMap.put("申请类型",e.getId().toString());
            }
        });

        ownerMap.put("研发编码",dataParam.getRDCode());
        ownerMap.put("质量编码",dataParam.getQCode());
        ownerMap.put("安全号",dataParam.getSecurityCode());
        ownerMap.put("部门内部编码",dataParam.getCodebyDept());
        ownerMap.put("是否紧急会签","true".equals(dataParam.getIsPromiseOrder()) ? "是" : "否");
        ownerMap.put("公司BU",dataParam.getBU());//苏州没有BU
        if(!dataParam.getPRItems().isEmpty()){
            for(DataDetails item : dataParam.getPRItems()){
                Map<String,String> entityMap = new HashMap<>();//子表信息
                entityMap.put("序号1",item.getItemNo());
                entityMap.put("物料代号",item.getPartNo());
                entityMap.put("物料或劳务摘要",item.getDescription());
                entityMap.put("固定资产预算号",item.getInvestmentNo());
                entityMap.put("预算金额",item.getBudgetAmount());
                entityMap.put("备注",item.getAdditionalRemark());
                entityMap.put("可否抵扣","true".equals(item.getDeductable()) ? "是" : "否");
                entityMap.put("数量",item.getQuantity());
                entityMap.put("需求日期",item.getRequestedDate());
                entityMap.put("单位",item.getUnit());
                entityList.add(entityMap);
            }
        }

        //附件
        List<Long> att = new ArrayList<>();
        if(dataParam.getAttachments() != null && !dataParam.getAttachments().isEmpty()){
            String[] split = dataParam.getAttachments().split(",");
            for(int i=0;i<split.length;i++){
                att.add(Long.valueOf(split[i]));
            }
        }


        map.put("appName","collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        Map<String, Object> data2 = new HashMap<String, Object>();
        if(dataParam.getBU().equals(XABU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.XA"));
            data2.put(BaseConfig.getConfig().getString("tablename.XA"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.XA"),entityList);
        }else if(dataParam.getBU().equals(WHBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.WH"));
            data2.put(BaseConfig.getConfig().getString("tablename.WH"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.WH"),entityList);
        }else if(dataParam.getBU().equals(TJBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.TJ"));
            data2.put(BaseConfig.getConfig().getString("tablename.TJ"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.TJ"),entityList);
        }else if(dataParam.getBU().equals(TYBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.TY"));
            data2.put(BaseConfig.getConfig().getString("tablename.TY"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.TY"),entityList);
        }else if(dataParam.getBU().equals(SZBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.SZ"));
            data2.put(BaseConfig.getConfig().getString("tablename.SZ"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.SZ"),entityList);
        }else if(dataParam.getBU().equals(SYBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.SY"));
            data2.put(BaseConfig.getConfig().getString("tablename.SY"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.SY"),entityList);
        }else if(dataParam.getBU().equals(GZBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.GZ"));
            data2.put(BaseConfig.getConfig().getString("tablename.GZ"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.GZ"),entityList);
        }else if(dataParam.getBU().equals(FSBU)){
            data1.put("templateCode", BaseConfig.getConfig().getString("templateCode.FS"));
            data2.put(BaseConfig.getConfig().getString("tablename.FS"),ownerMap);
            data2.put(BaseConfig.getConfig().getString("tabledetailname.FS"),entityList);
        }
        data1.put("draft", "0");
        data1.put("relateDoc", "");
        data1.put("subject", "");
        data1.put("attachments", att);
        data1.put("data", data2);

        map.put("data",data1);
        log.info("传输oa的参数{}",map.toString());
        return map;
    }

    /**
     * 组装重新发起的数据
     * @param id 数据id
     * @param stringObjectMap  组装好的数据
     * @return
     */
    public JSONObject assmbly(Long id,Map<String,Object> stringObjectMap,String bu){
        log.info("bu={}",bu);
        JSONObject redata = new JSONObject();
        CtpAffairEntity one = ctpAffairService.getOne(new QueryWrapper<CtpAffairEntity>().eq("form_recordid", id).eq("state", "1"));
        if(one != null){
            JSONObject data = new JSONObject();
            JSONObject jsonObject = new JSONObject(stringObjectMap);
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONObject data1Json = dataJson.getJSONObject("data");
            if(bu.equals(XABU)){
                log.info("西安进来啦!-------------");
                data = data1Json.getJSONObject(TABLENAMEXA);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.XA"));
                data.put("sub",jsonArray);
            }else if(bu.equals(WHBU)){
                data = data1Json.getJSONObject(TABLENAMEWH);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.WH"));
                data.put("sub",jsonArray);
            }else if(bu.equals(TJBU)){
                data = data1Json.getJSONObject(TABLENAMETJ);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.TJ"));
                data.put("sub",jsonArray);
            }else if(bu.equals(TYBU)){
                data = data1Json.getJSONObject(TABLENAMETY);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.TY"));
                data.put("sub",jsonArray);
            }else if(bu.equals(SZBU)){
                log.info("苏州进来啦！----------------");
                data = data1Json.getJSONObject(TABLENAMESZ);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.SZ"));
                data.put("sub",jsonArray);
            }else if(bu.equals(SYBU)){
                data = data1Json.getJSONObject(TABLENAMESY);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.SY"));
                data.put("sub",jsonArray);
            }else if(bu.equals(GZBU)){
                data = data1Json.getJSONObject(TABLENAMEGZ);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.GZ"));
                data.put("sub",jsonArray);
            }else if(bu.equals(FSBU)){
                data = data1Json.getJSONObject(TABLENAMEFS);
                JSONArray jsonArray = data1Json.getJSONArray(BaseConfig.getConfig().getString("tabledetailname.FS"));
                data.put("sub",jsonArray);
            }
            JSONArray attachments = dataJson.getJSONArray("attachments");
            //根据senderid查询登录名
            OrgPrincipalEntity login = orgPrincipalService.getOne(new QueryWrapper<OrgPrincipalEntity>().eq("member_id", one.getSenderId()));

            redata.put("attachments",attachments);
            redata.put("data",data);
            redata.put("transfertype","json");
            redata.put("affairId",one.getId().toString());
            redata.put("senderLoginName",login.getLoginName());
        }
        return redata;
    }


    public void remove(String bu,String prno) throws InterruptedException {
        Thread.sleep(5000);
        if(bu.equals(XABU)){
            List<Formmain0982Entity> list = formmain0982Service.list(new LambdaQueryWrapper<Formmain0982Entity>().eq(Formmain0982Entity::getField0002, prno)
                    .orderByAsc(Formmain0982Entity::getStartDate));
            log.info("查询元素{}",list.size());
            if(list.size() > 1){
                formmain0982Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(WHBU)){
            List<Formmain0979Entity> list = formmain0979Service.list(new LambdaQueryWrapper<Formmain0979Entity>().eq(Formmain0979Entity::getField0002, prno)
                    .orderByAsc(Formmain0979Entity::getStartDate));
            if(list.size() > 1){
                formmain0979Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(TJBU)){
            List<Formmain0977Entity> list = formmain0977Service.list(new LambdaQueryWrapper<Formmain0977Entity>().eq(Formmain0977Entity::getField0002, prno)
                    .orderByAsc(Formmain0977Entity::getStartDate));
            if(list.size() > 1){
                formmain0977Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(TYBU)){
            List<Formmain0975Entity> list = formmain0975Service.list(new LambdaQueryWrapper<Formmain0975Entity>().eq(Formmain0975Entity::getField0002, prno)
                    .orderByAsc(Formmain0975Entity::getStartDate));
            if(list.size() > 1){
                formmain0975Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(SZBU)){
            List<Formmain0973Entity> list = formmain0973Service.list(new LambdaQueryWrapper<Formmain0973Entity>().eq(Formmain0973Entity::getField0002, prno)
                    .orderByAsc(Formmain0973Entity::getStartDate));
            if(list.size() > 1){
                formmain0973Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(SYBU)){
            List<Formmain0971Entity> list = formmain0971Service.list(new LambdaQueryWrapper<Formmain0971Entity>().eq(Formmain0971Entity::getField0002, prno)
                    .orderByAsc(Formmain0971Entity::getStartDate));
            if(list.size() > 1){
                formmain0971Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(GZBU)){
            List<Formmain0969Entity> list = formmain0969Service.list(new LambdaQueryWrapper<Formmain0969Entity>().eq(Formmain0969Entity::getField0002, prno)
                    .orderByAsc(Formmain0969Entity::getStartDate));
            if(list.size() > 1){
                formmain0969Service.removeById(list.get(0).getId());
            }
        }else if(bu.equals(FSBU)){
            List<Formmain0967Entity> list = formmain0967Service.list(new LambdaQueryWrapper<Formmain0967Entity>().eq(Formmain0967Entity::getField0002, prno)
                    .orderByAsc(Formmain0967Entity::getStartDate));
            if(list.size() > 1){
                formmain0967Service.removeById(list.get(0).getId());
            }
        }
    }

    /**
     * 当oa回退至发起人时回传E2状态
     * @param id 数据id
     * @param bu 公司编码
     */
    @GetMapping("rollback")
    public void rollback(@RequestParam String id,@RequestParam String bu){
        log.info("oa插件的日志id{},bu{}",id,bu);
        JSONObject json = new JSONObject();

        JSONArray itemList = new JSONArray();//子表数据

        JSONArray attList = new JSONArray();//附件数据

        JSONArray processList = new JSONArray();//审批意见数据
        if(bu.equals(XABU)){
            Formmain0982Entity byId = formmain0982Service.getById(id);
            byId.setField0115("0");
            formmain0982Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",XABU);
            List<Formson0983Entity> detailList = formson0983Service.list(new QueryWrapper<Formson0983Entity>().eq("formmain_id",id));
            for (Formson0983Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }else if(bu.equals(WHBU)){
            Formmain0979Entity byId = formmain0979Service.getById(id);
            byId.setField0108("0");
            formmain0979Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",WHBU);
            List<Formson0980Entity> detailList = formson0980Service.list(new QueryWrapper<Formson0980Entity>().eq("formmain_id",id));
            for (Formson0980Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }else if(bu.equals(TJBU)){
            Formmain0977Entity byId = formmain0977Service.getById(id);
            byId.setField0087("0");
            formmain0977Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",TJBU);
            List<Formson0978Entity> detailList = formson0978Service.list(new QueryWrapper<Formson0978Entity>().eq("formmain_id",id));
            for (Formson0978Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }else if(bu.equals(TYBU)){
            Formmain0975Entity byId = formmain0975Service.getById(id);
            byId.setField0114("0");
            formmain0975Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",TYBU);
            List<Formson0976Entity> detailList = formson0976Service.list(new QueryWrapper<Formson0976Entity>().eq("formmain_id",id));
            for (Formson0976Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }else if(bu.equals(SZBU)){
            Formmain0973Entity byId = formmain0973Service.getById(id);
            byId.setField0097("0");
            formmain0973Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",SZBU);
            List<Formson0974Entity> detailList = formson0974Service.list(new QueryWrapper<Formson0974Entity>().eq("formmain_id",id));
            for (Formson0974Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }

        }else if(bu.equals(SYBU)){
            Formmain0971Entity byId = formmain0971Service.getById(id);
            byId.setField0116("0");
            formmain0971Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",SYBU);
            List<Formson0972Entity> detailList = formson0972Service.list(new QueryWrapper<Formson0972Entity>().eq("formmain_id",id));
            for (Formson0972Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }else if(bu.equals(GZBU)){
            Formmain0969Entity byId = formmain0969Service.getById(id);
            byId.setField0124("0");
            formmain0969Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",GZBU);
            List<Formson0970Entity> detailList = formson0970Service.list(new QueryWrapper<Formson0970Entity>().eq("formmain_id",id));
            for (Formson0970Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }else if(bu.equals(FSBU)){
            Formmain0967Entity byId = formmain0967Service.getById(id);
            byId.setField0087("0");
            formmain0967Service.updateById(byId);
            json.put("PRNo",byId.getField0002());
            json.put("Capital","固定资产".equals(byId.getField0048()) ? "1" : "0");
            json.put("InvestmentNo",byId.getField0029());
            json.put("BudgetAmount",byId.getField0032());
            json.put("BU",FSBU);
            List<Formson0968Entity> detailList = formson0968Service.list(new QueryWrapper<Formson0968Entity>().eq("formmain_id",id));
            for (Formson0968Entity detail : detailList) {
                JSONObject detailJson = new JSONObject();
                detailJson.put("ItemNo",detail.getField0008());
                detailJson.put("InvestmentNo",detail.getField0014());
                detailJson.put("BudgetAmount",detail.getField0036());
                itemList.add(detailJson);
            }
        }

        //正文数据
        CtpContentAllEntity contentDataId = ctpContentAllService.getOne(new QueryWrapper<CtpContentAllEntity>().eq("content_data_id", id));
        //附件信息
        List<CtpAttachmentEntity> att = ctpAttachmentService.list(new QueryWrapper<CtpAttachmentEntity>().eq("att_reference", contentDataId.getModuleId()).eq("sub_reference", contentDataId.getModuleId()));
        //协同信息
        ColSummaryEntity formRecordid = colSummaryService.getOne(new QueryWrapper<ColSummaryEntity>().eq("form_recordid", id));
        //评论信息
        List<CtpCommentAllEntity> list = ctpCommentAllService.list(new QueryWrapper<CtpCommentAllEntity>().eq("module_id", formRecordid.getId()).orderByDesc("create_date"));

        //个人事项表
        CtpAffairEntity aff = ctpAffairService.getById(list.get(0).getAffairId());
        if(!att.isEmpty()){
            for(CtpAttachmentEntity item : att){
                JSONObject attJson = new JSONObject();
                attJson.put("Id",item.getFileUrl());
                attJson.put("Attachment",item.getFilename());
                attJson.put("Remark","");
                attList.add(attJson);
            }
        }

        if(!list.isEmpty()){
            JSONObject commJson = new JSONObject();
            commJson.put("Processedby",orgMemberService.getById(list.get(0).getCreateId()).getCode());
            commJson.put("ProcessedTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(0).getCreateDate()));
            commJson.put("ReceivedTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(aff.getReceiveTime()));
            commJson.put("Approved","802");
            commJson.put("Comments",list.get(0).getContent());
            processList.add(commJson);
        }
        json.put("ItemList",itemList);
        json.put("AttachmentList",attList);
        json.put("ProcessList",processList);
        log.info("传递的参数={}",json.toJSONString());
        String cghtUrl = HttpRequest.post(BaseConfig.getConfig().getString("cghtUrl")).body(json.toJSONString()).execute().body();
        log.info("e2返回信息{}",cghtUrl);

    }

    /**
     * 提交数据
     * @param data 表单数据
     * @param token 令牌
     * @param status 0-发起 1-重新发起
     * @return 返回结果
     */
    public String sumbit(String data,String token,Integer status,String bu){
        String result = null;
        if(status == 0){
            result = HttpRequest.post(BaseConfig.getConfig().getString("confirmUrlZS"))
                    .header("token", token)
                    .body(data)
                    .execute()
                    .body();
        }else if(status == 1){
            String url = null;
            if(bu.equals(XABU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.XA");
            }else if(bu.equals(WHBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.WH");
            }else if(bu.equals(TJBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.TJ");
            }else if(bu.equals(TYBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.TY");
            }else if(bu.equals(SZBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.SZ");
            }else if(bu.equals(SYBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.SY");
            }else if(bu.equals(GZBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.GZ");
            }else if(bu.equals(FSBU)){
                url = BaseConfig.getConfig().getString("reConfirmUrlZS") +  BaseConfig.getConfig().getString("templateCode.FS");
            }
            result = HttpRequest.post(url)
                    .header("token", token)
                    .body(data)
                    .execute()
                    .body();
        }
        return result;
    }
    /**
     * 当采购系统中取消时调用该接口，OA中删除该待办事项和单据数据
     * @param PRNo 采购系统中的采购编号
     * @param BU 公司编码
     * @return 返回结果
     */
    @RequestMapping("cancelOa")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject cancelOa(@RequestParam String PRNo, @RequestParam String BU) {
        JSONObject jsonObject = new JSONObject();
        
        try {
            // 参数验证
            if (PRNo == null || PRNo.trim().isEmpty() || BU == null || BU.trim().isEmpty()) {
                jsonObject.put("code", 400);
                jsonObject.put("msg", "参数不能为空");
                jsonObject.put("form_id", null);
                return jsonObject;
            }
            
            //根据BU判断是那个公司的采购申请书，对应不同的表单和字段
            String fieldx = "";
            String tablename = "";
            if (BU.equals(XABU)) {
                fieldx = FIELDXA;
                tablename = TABLENAMEXA;
            } else if (BU.equals(WHBU)) {
                fieldx = FIELDWH;
                tablename = TABLENAMEWH;
            } else if (BU.equals(TJBU)) {
                fieldx = FIELDTJ;
                tablename = TABLENAMETJ;
            } else if (BU.equals(TYBU)) {
                fieldx = FIELDTY;
                tablename = TABLENAMETY;
            } else if (BU.equals(SZBU)) {
                fieldx = FIELDSZ;
                tablename = TABLENAMESZ;
            } else if (BU.equals(SYBU)) {
                fieldx = FIELDSY;
                tablename = TABLENAMESY;
            } else if (BU.equals(GZBU)) {
                fieldx = FIELDGZ;
                tablename = TABLENAMEGZ;
            } else if (BU.equals(FSBU)) {
                fieldx = FIELDFS;
                tablename = TABLENAMEFS;
            } else {
                jsonObject.put("code", 400);
                jsonObject.put("msg", "不支持的公司编码: " + BU);
                jsonObject.put("form_id", null);
                return jsonObject;
            }
            
            //根据采购申请号查询对应的单据
            String sql = "select id from " + tablename + " where " + fieldx + "=?";
            List<String> resultList = jdbcTemplate.queryForList(sql, String.class, PRNo);
            
            if (resultList == null || resultList.isEmpty()) {
                jsonObject.put("code", 404);
                jsonObject.put("msg", "未找到对应的采购申请记录，PRNo: " + PRNo);
                jsonObject.put("form_id", null);
                return jsonObject;
            }
            
            String s = resultList.get(0);
            if (s == null || s.trim().isEmpty()) {
                jsonObject.put("code", 404);
                jsonObject.put("msg", "查询到的记录ID为空");
                jsonObject.put("form_id", null);
                return jsonObject;
            }
            
            //根据单据号删除待办事项
            String sql1 = "delete from CTP_AFFAIR where form_recordid=?";
            jdbcTemplate.update(sql1, s);
            
            //根据id删除summary数据
            String sql2 = "delete from COL_SUMMARY where FORM_RECORDID=?";
            jdbcTemplate.update(sql2, s);
            
            //根据id删除表单数据
            String sql3 = "delete from " + tablename + " where id=?";
            jdbcTemplate.update(sql3, s);
            
            jsonObject.put("code", 200);
            jsonObject.put("msg", "取消成功");
            jsonObject.put("form_id", s);
            
        } catch (Exception e) {
            log.error("cancelOa方法执行异常，PRNo: {}, BU: {}, 错误信息: {}", PRNo, BU, e.getMessage(), e);
            jsonObject.put("code", 500);
            jsonObject.put("msg", "系统异常: " + e.getMessage());
            jsonObject.put("form_id", null);
        }
        
        return jsonObject;
    }


}
